package com.googlecode.contests_repo.validation;

import java.io.*;
import java.util.*;

import com.googlecode.contests_repo.core.model.Problem;

/**
 * A validation helper class used to validate the structure of a series folder.
 * 
 * @author joro, petko
 * 
 */
public class SeriesValidator extends ResourceValidator {

	/**
	 * Checks whether the given series folder contains valid contests for the
	 * series. Uses series-schema.json file for the validation.
	 * 
	 * @param folderPath
	 *            the path to the folder resource to validate
	 * @return a list of all validation errors
	 */
	@Override
	public synchronized List<String> validate(String folderPath) {
		List<String> errors = super.validate(folderPath);
		if (errors.size() == 1 && errors.get(0).contains("does not exist")) {
			return errors;
		}
		File folder = new File(folderPath);

		// append contest errors
		ContestValidator contestValidator = new ContestValidator();
		List<File> contestList = ValidationTools.getResourceSubfolders(folder);
		for (File contest : contestList) {
			List<String> contestErrors = contestValidator.validate(contest
					.getAbsolutePath());
			errors.addAll(contestErrors);
		}

		totalFilesCount += contestList.size();
		//Ignore hidden files
		int expectedFilesCount = folder.listFiles(new FileFilter() {
					public boolean accept(File file) {
						return !file.isHidden();
					}
				}).length;
		
		if (expectedFilesCount != totalFilesCount) {
			errors.add(String.format("Folder %s contains superfluous files.",
					folder));
		}

		return errors;
	}

	@Override
	protected boolean jsonExists(List<String> errors, File folder,
			List<File> fileList) {
		File seriesJasonFile = new File(folder, "series.json");
		if (!fileList.contains(seriesJasonFile)) {
			errors.add(String
					.format("Folder %s does not contain a \"series.json\" file definition.",
							folder.getAbsolutePath()));
			return false;
		} else {
			List<String> validationErrors = ValidationTools.validateJson(
					seriesJasonFile, Problem.class);
			errors.addAll(validationErrors);
			return true;
		}
	}
}
